import axios from 'axios'
import { ElLoading } from 'element-plus'
import 'element-plus/dist/index.css'

const instance = axios.create({
  baseURL: 'http://localhost:8888/api/',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// Loading类
class Loading {
  constructor() {
    this.loadingInstance = null
    this.counter = 0
  }

  // 显示loading
  show() {
    if (this.counter === 0) {
      this.loadingInstance = ElLoading.service({
        fullscreen: true,
        lock: true,
        text: '加载中...',
        // spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        delay: 500,
        duration: 2000, // 显示时间为2秒
      })
    }
    this.counter++
  }

  // 隐藏loading
  hide() {
    this.counter--
    if (this.counter === 0 && this.loadingInstance) {
      this.loadingInstance.close()
    }
  }
}

const loading = new Loading()

instance.interceptors.request.use(
  (config) => {
    loading.show() // 显示loading
    return config
  },
  (error) => {
    loading.hide()
    return Promise.reject(error)
  },
)

instance.interceptors.response.use(
  (response) => {
    loading.hide()
    return response
  },
  (error) => {
    loading.hide()
    if (error.response) {
      // 根据状态码进行错误处理
      switch (error.response.status) {
        case 401:
          // 用户未登录，跳转到登录页
          break
        case 403:
          // 用户无权限访问，跳转到错误页
          break
        case 404:
          // 请求的资源不存在，跳转到错误页
          break
        default:
          // 其他错误，跳转到错误页
          break
      }
    } else {
      // 请求超时或网络错误
    }
    return Promise.reject(error)
  },
)

export default {
  get(url, config = {}) {
    return instance.get(url, config)
  },
  post(url, data = {}, config = {}) {
    return instance.post(url, data, config)
  },
  put(url, data = {}, config = {}) {
    return instance.put(url, data, config)
  },
  delete(url, config = {}) {
    return instance.delete(url, config)
  },
}
